//
//  BanBu_IceBreakerController.m
//  BanBu
//
//  Created by mac on 12-8-18.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BanBu_IceBreakerController.h"
#import "BanBu_ChatViewController.h"
#import "AppDataManager.h"
#import "TKLoadingView.h"
//#import "BanBu_IceCell.h"
#import "BanBu_IceTextCell.h"
#import "BanBu_IceBreaker_Voice.h"
#import "BanBu_icePicController.h"
#import "WXOpen.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "BanBu_ChatCellAPI.h"
#import "BanBuAPIs.h"

@interface BanBu_IceBreakerController ()

@end

@implementation BanBu_IceBreakerController
@synthesize dataArray = _dataArray;


-(void)dealloc
{
    [_dataArray release],_dataArray=nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    BanBu_NavButton *reButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    reButton.position = ButtonPositionRight;
    reButton.frame = CGRectMake(0, 0, 40, 30);
    [reButton addTarget:self action:@selector(refreshContent) forControlEvents:UIControlEventTouchUpInside];
    [reButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:reButton] autorelease];
    
    if(!self.title)
    {
        self.title = NSLocalizedString(@"ice_textTitle", nil);
    }

    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
}
-(void)refreshContent
{
    [self setRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [AppComManager cancalHandlesForObject:self];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(!self.dataArray.count)
    {
        [self setRefreshing];
    }
}

//点击更多

-(void)moreContent{
//    UIActionSheet *conSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"文字破冰语",@"图片破冰语",@"语音破冰语",nil];
//    [conSheet showInView:self.view];
//    [conSheet release];
}

-(void)popToChat
{
    BanBu_ChatViewController *chat = nil;
    for(UIViewController *vc in [self.navigationController viewControllers])
        if([vc isKindOfClass:[BanBu_ChatViewController class]])
        {
            chat = (BanBu_ChatViewController *)vc;
            break;
        }
    if(chat)
    {
        [self.navigationController popToViewController:chat animated:YES];
    }
    else
    {
        BanBu_ChatViewController *chat=[[BanBu_ChatViewController alloc]init];
        
        [self.navigationController pushViewController:chat animated:YES];
        [chat release];
    }
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if(actionSheet.tag == 502)
    {
        if(buttonIndex == 0)
        {
            NSDictionary * sendDic = [NSDictionary dictionaryWithObjectsAndKeys:[[_dataArray objectAtIndex:selectedRow] valueForKey:@"saytext"],KeyContent,[NSNumber numberWithInt:ChatCellTypeText],KeyType,@"pb",KeyShowFrom, nil];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
            [self popToChat];
        }
        else if(buttonIndex == 1)
        {
            //复制到粘贴板
            UIPasteboard *paste = [UIPasteboard generalPasteboard];
            
            paste.string = [[_dataArray objectAtIndex:selectedRow] valueForKey:@"saytext"];
            
            [self popToChat];
        }
    }
    else
    {
        if(buttonIndex == 0)
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"selectSignature" object:[[_dataArray objectAtIndex:selectedRow] valueForKey:@"saytext"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    }
    
    // 去掉以前的Banbu_dynamiccell
    for(BanBu_IceTextCell *banbucell in cell.contentView.subviews)
    {
        if([banbucell isKindOfClass:[BanBu_IceTextCell class]])
        {
            [banbucell removeFromSuperview];
            break;
        }
    }
    BanBu_IceTextCell *mycell=[[BanBu_IceTextCell alloc]initWithFrame:CGRectZero];
    [cell.contentView addSubview:mycell];
    mycell.saytextStr = [[_dataArray objectAtIndex:indexPath.row] valueForKey:@"saytext"];
    
    if(![[[_dataArray objectAtIndex:indexPath.row] valueForKey:@"extend"] isEqualToString:@""])
    {
        mycell.extendStr = [[_dataArray objectAtIndex:indexPath.row] valueForKey:@"extend"];
    }

    
    [mycell backImage:mycell.frame];
    
    cell.frame = mycell.frame;
    [mycell release];

    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [self heightForText:[[_dataArray objectAtIndex:indexPath.row] valueForKey:@"saytext"]]+10;
    
    if(![[[_dataArray objectAtIndex:indexPath.row] valueForKey:@"extend"] isEqualToString:@""])
    {
        height += [self heightForText:[[_dataArray objectAtIndex:indexPath.row] valueForKey:@"extend"]];
    }
    
    return height;
}

-(float)heightForText:(NSString *)text
{
    NSArray *smiles = [SmileStr componentsSeparatedByString:@"|"];
    for(NSString *aSmile in smiles)
    {
        text = [text stringByReplacingOccurrencesOfString:aSmile withString:@"ww"];
    }
    
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
    
    return size.height;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    selectedRow = indexPath.row;
    if(!_isFromProfile)
    {
        //从聊天界面进来
        UIActionSheet *conSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),NSLocalizedString(@"copyButton", nil),nil];
        conSheet.tag = 502;
        [conSheet showInView:self.view];
        [conSheet release];
    }
    else
    {
        UIActionSheet *conSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmChange", nil),nil];
        conSheet.tag = 503;
        [conSheet showInView:self.view];
        [conSheet release];
    }
}


-(void)loadingData
{
    [self.parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [AppComManager getBanBuData:BanBu_Get_Sayhi_Rand par:self.parDic delegate:self];
    aBNC = (BanBu_NavigationController *)self.navigationController;
    aBNC.isLoading = YES;
}

#pragma mark - BanBuDelegate

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    aBNC.isLoading = NO;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        [self finishedLoading];

        return;
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Sayhi_Rand]){
        if([[resDic valueForKey:@"ok"]boolValue]&&[[[[resDic valueForKey:@"list"] objectAtIndex:0] valueForKey:@"kind"] isEqual:@"t"])
        {
            NSArray *listArr = [[NSArray alloc]initWithArray:[resDic valueForKey:@"list"]];
            self.dataArray = listArr;
            [listArr release];
            [self.tableView reloadData];
        }
        else if([[resDic valueForKey:@"ok"]boolValue]&&[[[[resDic valueForKey:@"list"] objectAtIndex:0] valueForKey:@"kind"] isEqual:@"i"])
        {
            BanBu_icePicController *picBanbu=[[BanBu_icePicController alloc]initWithDictionary:resDic];
            
            [self.navigationController pushViewController:picBanbu animated:NO];
            
            [picBanbu release];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
    }
    [self finishedLoading];
}



@end
